import Axios from 'axios';
import { Toast } from 'vant';
import handleCode from '../handler/handleReponse';
import { apiHost } from '@/config/index';
import store from '@/store/index';
console.log(apiHost);
const HTTP = Axios.create({
	baseURL: process.env.VUE_APP_MOCK == true ? `${apiHost}/mock` : `${apiHost}/api`,
});

HTTP.defaults.withCredentials = true;

HTTP.interceptors.request.use(
	(config) => {
		if (store.state.user.token) {
			config.headers['Authorization'] = store.state.user.token;
		} else {
			config.headers['Authorization'] = null;
		}
		// if (config.method == 'get') {
		// 	config.params = {
		// 		...config.params,
		// 	};
		// }
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

HTTP.interceptors.response.use(
	(response) => {
		if (response.status !== 200) {
			return Promise.reject('error');
		} else {
			//状态码处理
			const params = response.data;
			params.code = params.code ? params.code : [];
			const res = handleCode(response.data, params.code);
			return res;
		}
	},
	(error) => {
		if(error.response.status==500){
			Toast('后端服务器离线中');
			return
		};
		if (!navigator.onLine) {
			Toast('当前网络为离线状态');
		}
		return Promise.reject(error);
	}
);

const Request = {
	get({ url, params }) {
		return HTTP.get(url, {
			params: params,
		});
	},

	post({ url,params,config }) {
		return HTTP.post(url,params,config);
	},
};

export default Request;
